/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.utils

import com.google.common.collect.ArrayListMultimap
import cool.taomu.toolkit.crypto.Base64
import java.io.File
import java.io.FileInputStream
import java.util.List
import java.util.Map
import java.util.Properties
import java.util.UUID
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import org.apache.oro.text.perl.Perl5Util
import org.yaml.snakeyaml.Yaml

class YamlUitls {

	def Properties toProperties(String filename) {
		val m = ArrayListMultimap.create();
		var yml = new Yaml()
		var results = yml.loadAs(TaomuResource.read(filename), Map)
		results.forEach [ k, v |
			if (v instanceof Map) {
				toProperty(m, k, v)
			} else if (v instanceof List) {
				v.forEach [
					toProperty(m, k, it)
				]
			} else {
				m.put(k, v);
			}
		]
		val pfile = File.createTempFile(UUID.randomUUID.toString, ".properties");
		val pro = new Properties();
		m.asMap.forEach [ k, v1 |
			var p5 = new Perl5Util();
			var v = v1.get(0);
			if (v instanceof String && p5.match("/^ENC\\(([^?.]*)\\)$/", v as String)) {
				var dev = new String(new Base64(p5.group(1).bytes).decode, "UTF-8");
				FileUtils.writeStringToFile(pfile, #[k, dev].join("=") + "\n", "UTF-8", true);
			}else if(v1 instanceof List){
				FileUtils.writeStringToFile(pfile, #[k, v1.join(",")].join("=") + "\n", "UTF-8", true);
			} else {
				FileUtils.writeStringToFile(pfile, #[k, v].join("=") + "\n", "UTF-8", true);
			}
		]		try(var in = new FileInputStream(pfile)) {
			pro.load(in);
			pfile.delete();
		}
		return pro;
	}

	def void toProperty(ArrayListMultimap<String, Object> convert, String key, Map<String, Object> map) {
		map.forEach [ k, v |
			val String namespace = StringUtils.isNotBlank(key) ? #[key, k].join(".") : k
			if (v instanceof Map) {
				toProperty(convert, namespace, v);
			} else if (v instanceof List) {
				v.forEach [
					if(it instanceof Map){
						toProperty(convert, namespace, it)
					}else{
						if(convert.containsKey(namespace)){
							convert.put(namespace,it);
						}else{
							convert.put(namespace, it);
						}
					}
				]
			} else {
				convert.put(namespace, v);
			}
		]
	}
}
